package com.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.constant.WorkConstant;
import com.zb.entity.AccounLoginInfo;
import com.zb.entity.ZjWorkOrder;
import com.zb.entity.ZjWorkRemark;
import com.zb.entity.ZjWorkRemarkAnnex;
import com.zb.extend.WorkOrderExtend;
import com.zb.mapper.ZjWorkRemarkMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjWorkLeaveMessageService;
import com.zb.service.ZjWorkOrderService;
import com.zb.service.ZjWorkRemarkAnnexService;
import com.zb.service.ZjWorkRemarkService;
import com.zb.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 工单备注表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2024-04-02
 */
@Service
public class ZjWorkRemarkServiceImpl extends ServiceImpl<ZjWorkRemarkMapper, ZjWorkRemark> implements ZjWorkRemarkService {
    @Resource
    private ZjWorkOrderService workOrderService;
    @Resource
    private ZjWorkRemarkAnnexService workRemarkAnnexService;
    @Resource
    private ZjWorkLeaveMessageService workLeaveMessageService;

    // 保存工单备注
    @Override
    @Transactional
    public void save(AccounLoginInfo loginInfo, WorkRemarkVo remarkVo) {
        QueryWrapper<ZjWorkOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.select("code", "status")
                .in("id", remarkVo.getWorkIds());
        List<ZjWorkOrder> orderList = workOrderService.list(orderQueryWrapper);
        List<String> workNos = orderList.stream().filter(f -> f.getStatus() == WorkConstant.WORK_STATUS_4 || f.getStatus() == WorkConstant.WORK_STATUS_5).map(ZjWorkOrder::getCode).toList();
        Assert.isTrue(CollectionUtil.isEmpty(workNos), "当前工单流程已完成或已取消，不允许操作：" + String.join("、", workNos));

        List<ZjWorkRemark> remarkList = new ArrayList<>();
        ZjWorkRemark remark = null;
        List<ZjWorkRemarkAnnex> remarkAnnexes = new ArrayList<>();
        ZjWorkRemarkAnnex remarkAnnex = null;
        List<OrderLeaveMessage> messageList = new ArrayList<>();
        for (Integer visitType : remarkVo.getVisitTypes()) {
            for (Long workId : remarkVo.getWorkIds()) {
                remark = new ZjWorkRemark();
                remark.setId(IdWorker.getId());
                remark.setCustAccId(loginInfo.getCustAccId());
                remark.setWorkId(workId);
                remark.setRemark(remarkVo.getRemark());
                remark.setCreateEmpType(1);
                remark.setCreateEmpId(loginInfo.getId());
                remark.setCreateEmp(loginInfo.getName());
                remarkList.add(remark);
                messageList.add(new OrderLeaveMessage()
                                .setCustAccId(loginInfo.getCustAccId())
                                .setWorkId(workId)
                                .setWorkNo(orderList.stream().filter(f -> Objects.equals(f.getId(), workId)).findFirst().map(ZjWorkOrder::getCode).orElse(""))
                                .setVisitType(visitType)
                                .setEmpType(1)
                                .setEmpId(loginInfo.getId())
                                .setEmp(loginInfo.getName())
                                .setContent(remarkVo.getRemark())
                                .setAnnexs(remarkVo.getAnnexs()));
                if (CollectionUtil.isNotEmpty(remarkVo.getAnnexs())) {
                    for (String annex : remarkVo.getAnnexs()) {
                        remarkAnnex = new ZjWorkRemarkAnnex();
                        remarkAnnex.setId(IdWorker.getId());
                        remarkAnnex.setCustAccId(loginInfo.getCustAccId());
                        remarkAnnex.setWorkId(workId);
                        remarkAnnex.setWorkRemarkId(remark.getId());
                        remarkAnnex.setPath(annex);
                        remarkAnnexes.add(remarkAnnex);
                    }
                }
            }

        }
        this.saveBatch(remarkList);
        if (CollectionUtil.isNotEmpty(remarkAnnexes)) {
            workRemarkAnnexService.saveBatch(remarkAnnexes);
        }
        workLeaveMessageService.save(messageList);
    }

    // 根据工单ID获取工单备注列表
    @Override
    public Map<String, Object> getWorkReamrks(Long workId, PageUtil pageUtil) {
        PageUtil.setPageLimit(pageUtil);
        QueryWrapper<ZjWorkRemark> wrapper = new QueryWrapper<>();
        wrapper.select("id", "remark", "gmt_create")
                .eq("work_id", workId);
        Page<ZjWorkRemark> page = this.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), wrapper);
        List<ZjWorkRemarkAnnex> annexes = workRemarkAnnexService.getByWorkRemarkIds(page.getRecords().stream().map(ZjWorkRemark::getId).toList());
        return PageUtil.pageList(page.getCurrent(), page.getPages(), page.getTotal(), page.getRecords().stream().map(remark -> {
            WorkRemarkListVo vo = new WorkRemarkListVo();
            vo.setId(remark.getId());
            vo.setRemark(remark.getRemark());
            vo.setCreateTime(remark.getGmtCreate());
            vo.setAnnes(annexes.stream().filter(f -> Objects.equals(f.getWorkRemarkId(), remark.getId())).map(ZjWorkRemarkAnnex::getPath).toList());
            return vo;
        }).toList());
    }
}
